using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace System.Utility.Helper
{
	public class Serialize
	{
		public Serialize()
		{
		}

		public static T DeSerializeFromBinary<T>(string fileName)
		where T : class
		{
			T t;
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			FileStream fileStream = new FileStream(fileName, FileMode.Open);
			try
			{
				t = (T)(binaryFormatter.Deserialize(fileStream) as T);
			}
			finally
			{
				if (fileStream != null)
				{
					((IDisposable)fileStream).Dispose();
				}
			}
			return t;
		}

		public static T DeSerializeFromXML<T>(string xmlFile)
		where T : class
		{
			T t;
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
			FileStream fileStream = new FileStream(xmlFile, FileMode.Open);
			try
			{
				t = (T)(xmlSerializer.Deserialize(fileStream) as T);
			}
			finally
			{
				if (fileStream != null)
				{
					((IDisposable)fileStream).Dispose();
				}
			}
			return t;
		}

		public static T DeSerializeToObject<T>(string s)
		where T : class
		{
			T t;
			StringReader stringReader = new StringReader(s);
			try
			{
				t = (T)(new XmlSerializer(typeof(T))).Deserialize(stringReader);
			}
			finally
			{
				if (stringReader != null)
				{
					((IDisposable)stringReader).Dispose();
				}
			}
			return t;
		}

		public static void SerializeToBinary(object instance, string fileName)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			FileStream fileStream = new FileStream(fileName, FileMode.Create);
			try
			{
				binaryFormatter.Serialize(fileStream, instance);
			}
			finally
			{
				if (fileStream != null)
				{
					((IDisposable)fileStream).Dispose();
				}
			}
		}

		public static void SerializeToXML<T>(T instance, string xmlFile)
		{
			XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
			FileStream fileStream = new FileStream(xmlFile, FileMode.Create);
			try
			{
				xmlSerializer.Serialize(fileStream, instance);
			}
			finally
			{
				if (fileStream != null)
				{
					((IDisposable)fileStream).Dispose();
				}
			}
		}

		public static string SerializeToXML<T>(T instance)
		{
			string str;
			StringWriter stringWriter = new StringWriter();
			try
			{
				XmlSerializer xmlSerializer = new XmlSerializer(instance.GetType());
				xmlSerializer.Serialize(stringWriter, instance);
				str = stringWriter.ToString();
			}
			finally
			{
				if (stringWriter != null)
				{
					((IDisposable)stringWriter).Dispose();
				}
			}
			return str;
		}
	}
}